package com.solution.common.exception;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.solution.common.utils.json.JSONUtils;
/**
 * 全局异常处理类
 * @author llp
 * @date 2017/4/19 10:55
 */
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
        // 日志记录异常message和stacktrace
        logger.error(ex.getMessage(),ex);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("exception", ex.getMessage());
        map.put("exceptionDetails", ex.getCause());
        if(ex instanceof IncorrectCredentialsException || ex instanceof UnknownAccountException){
        	// 登录认证失败
        	return new ModelAndView("redirect:/login.jsp?error=1");
        }else if(ex instanceof UnauthenticatedException || ex instanceof UnauthorizedException){
        	// 越权访问跳转页面
        	return new ModelAndView("redirect:/page/error/403.jsp");
        }
        String header = request.getHeader("X-Requested-With");
        // 处理异步请求
        if (StringUtils.isNotBlank(header) && (header.equals("X-Requested-With") || header.equals("XMLHttpRequest"))) {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = null;
            try {
                pw = response.getWriter();
                pw.write(JSONUtils.toJsonString(map));
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (pw != null)
                    pw.close();
            }
            return null;
        }
        // 跳转错误页面
        return new ModelAndView("/error/500", map);
    }

}